package top.lywivan.search.service.impl;

import com.alibaba.fastjson.JSON;
import top.lywivan.common.pojo.Question;
import top.lywivan.search.service.SearchService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public List<Question> searchWildcardQuestion(String question) {
        List<Question> list=new ArrayList<>();
        SearchRequest searchRequest=new SearchRequest("question");
        SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.wildcardQuery("question","*"+question+"*"));
        //searchSourceBuilder.from(0);
        //searchSourceBuilder.size(3);
        searchRequest.source(searchSourceBuilder);
        try {
            SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
            SearchHit[] hits = searchResponse.getHits().getHits();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                Question result = JSON.parseObject(json, Question.class);
                list.add(result);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
